%SimulationProgressBarSingleton.instance();
%clear_classes;
SingletonInitializer.create_all_singletons();
params = ParamsSingleton.instance();

rng('default');

% number_of_nodes = 30;
% max_rad = 300;
% top = Topology(number_of_nodes,max_rad,max_rad,true);

top = Topology.read_topology_from_file('topologies\topology_30_nodes.mat',params.router_type_DIJKSTRA);
number_of_nodes = length(top.nodes);

global_depositor = GlobalPacketDepositor.instance();
global_depositor.set_nodes(top.nodes);
sta_manager = StatisticsManager.instance();
sta_manager.set_topology(top);
params.link_loss_rate_in_precentage = 20;
src = 0;
dest = 0;

% for i=1:number_of_nodes
%     for j=1:number_of_nodes
%         if (i~=j)&&(top.nodes(i).distance_vector(j) ~=inf)&&(top.nodes(i).distance_vector(j) ~=0)
%             src = i;
%             dest = j;
%             break;
%         end
%     end
% end

src = 2;
dest = 12;

if src == 0
    error('no link found');
end

id = 555;
packet_size = 500;
src_node = top.nodes(src);
dest_node = top.nodes(dest);
romer_alpha = 0.2;
romer_c_source = top.nodes(src).distance_vector(dest);
remaining_credit = 2 * romer_c_source;
pack = RomerPacket(id, packet_size, src_node, dest_node, [], romer_alpha, remaining_credit, romer_c_source);

utils = Utils.instance();
str = sprintf('routing from source %d to dest %d\n', src, dest);
utils.trace(str);

% pack2 = pack.duplicate_packet();
% pack2.src_node =dest_node;
% pack2.dest_node = src_node;
% CBRPacketGenerator(pack2, source_data_rate);

source_data_rate = 500;
for i=1:4
    CBRPacketGenerator(pack, source_data_rate);
end

packets_manager = PacketsManager.instance();
% for i=1:100
%     packets_manager.create_new_packet(pack);
% end

ck = ClockSingleton.instance();
tick_counts = params.simulation_time_in_msec / params.clock_tick_delta_in_msec;
fprintf('number of ticks:%d\n',tick_counts);
for j=1:tick_counts
    fprintf('tick number : %d\n',j);
    ck.tick();
end

params.should_disable_all_traffic_generators = true;

network_dead = false;
while ~network_dead
    fprintf('tick number : %d\n',ck.tick_count);
    ck.tick();
    network_dead =  true;
    for j=1:length(top.nodes)
        if ~top.nodes(j).is_node_idle()
            network_dead = false;
			break;
        end
    end
end


packets_manager = PacketsManager.instance();
delivered_packets = packets_manager.delivered_multi_packets;

for i=1:length(delivered_packets)
    packet = delivered_packets(i).packet;
    fprintf('source node: %d.  dest node: %d. route length: %d\n',packet.src_node.id,packet.dest_node.id,length(packet.route));
    packet_route = packet.route;
    for j=1:length(packet_route);
        if j~=length(packet_route)
            fprintf('%d =>',packet_route(j));
        else
            fprintf('%d\n',packet_route(j));
        end
    end
end

utils =  Utils.instance();
sta_manager.get_and_print_statistics();

